package com.jinlia.show.modules.wxapp.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/image")
public class ImageController {
    @Value("${file.path}")
    public String filePath;

    @GetMapping(value = "{imgName}")
    public ResponseEntity<Resource> getImageAsByteArray(@PathVariable("imgName") String imgName) throws IOException {
        try {
            // 读取图片文件
            FileInputStream fileInputStream = new FileInputStream(filePath + imgName + ".WEBP");
            // 创建InputStreamResource对象
            Resource resource = new InputStreamResource(fileInputStream);
            // 设置HTTP headers
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=image.webp");
            headers.add(HttpHeaders.CONTENT_TYPE, "image/webp"); // 手动设置Content-Type
            // 返回图片
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);

        } catch (Exception e) {
            return ResponseEntity.unprocessableEntity().build();
        }
    }
}
